package com.load.service;

import com.load.config.UpLoadPathConfig;
import com.utils.JsonUtil;
import com.utils.TimeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * Created by 78397 on 2019/11/8.
 */

@Service
public class UpLoadService {

    @Autowired
    UpLoadPathConfig upLoadPathConfig;

    /**
     * 上传图片
     * @param file
     * @return
     * @throws java.io.IOException
     */
    public String uploadImg(MultipartFile file)throws IOException {

        String res = TimeUtil.getNow("HHmmss-")+ UUID.randomUUID();
        //图片服务器存储路径
        String rootPath = upLoadPathConfig.getUploadImgPath();
        //原始名称
        String originalFilename = file.getOriginalFilename();
        //新的文件名称
        String newFileName = res+originalFilename.substring(originalFilename.lastIndexOf("."));
        //创建年月文件夹
        Calendar date = Calendar.getInstance();
        File dateDirs = new File(date.get(Calendar.YEAR) + File.separator + (date.get(Calendar.MONTH)+1)+ File.separator + (date.get(Calendar.DATE)));
        //新文件
        File newFile = new File(rootPath+File.separator+dateDirs+File.separator+newFileName);
        //判断目标文件所在的目录是否存在
        if(!newFile.getParentFile().exists()){
            //如果目标文件所在的目录不存在，则创建父目录
            newFile.getParentFile().mkdirs();
        }
        System.out.println(newFile);
        //将内存中的数据写入磁盘
        file.transferTo(newFile);
        //完整的url
        String fileUrl = upLoadPathConfig.getServiceURL()+"/image/"+date.get(Calendar.YEAR)+"/"+(date.get(Calendar.MONTH)+1)+"/"+date.get(Calendar.DATE)+"/"+newFileName;
        Map<String,Object> map = new HashMap<>();
        Map<String,Object> map2 = new HashMap<>();
        map.put("code",0);//0表示成功，1失败
        map.put("msg","上传成功");//提示消息
        map.put("data",map2);
        map2.put("src",fileUrl);//图片url
        map2.put("title",newFileName);//图片名称，这个会显示在输入框里
        return JsonUtil.ObjectToJson2(map);
    }
}
